package com.thinkfit.jy.utils;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.thinkfit.jy.R;
import com.thinkfit.jy.activity.FreeMovementNewActivity;
import com.thinkfit.jy.serialport.SportType;


public class ShowBackButtonViewUtils {
    private static ShowBackButtonViewUtils mShowBackButtonViewUtils;
    private WindowManager windowManager;
    private View inflate;
    private Context mContext;
    private ImageView mBackButton, mLeftButton, mRightButton, mTopButton, mDownButton, hideBtton;
    private TextView mConfirmButton;
    private boolean isFist = true;

    private WindowManager.LayoutParams layoutParams;

    private int initialX;
    private int initialY;
    private float initialTouchX;
    private float initialTouchY;
    private int screenWidth;
    private long touchStartTime;
    private boolean isTounch = false;
    private LinearLayout mLayout,bottomLayout;
    private RelativeLayout topLayout,middleLayout;

    public static ShowBackButtonViewUtils getInstance() {
        if (mShowBackButtonViewUtils == null) {
            mShowBackButtonViewUtils = new ShowBackButtonViewUtils();
        }
        return mShowBackButtonViewUtils;
    }

    public void ShowBackButtonView(Context context) {
        this.mContext = context;
        if (windowManager == null) {
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        if (inflate == null) {
            inflate = LayoutInflater.from(context).inflate(R.layout.item_show_backbutton, null);
            mLayout = inflate.findViewById(R.id.cl_layout);
            bottomLayout = inflate.findViewById(R.id.ll_bottom);
            topLayout = inflate.findViewById(R.id.rl_top);
            middleLayout = inflate.findViewById(R.id.rl_middle);
            mBackButton = inflate.findViewById(R.id.tv_back);
            mLeftButton = inflate.findViewById(R.id.tv_left);
            mRightButton = inflate.findViewById(R.id.tv_right);
            mTopButton = inflate.findViewById(R.id.tv_up);
            mDownButton = inflate.findViewById(R.id.tv_down);
            mConfirmButton = inflate.findViewById(R.id.tv_confirm);
            hideBtton = inflate.findViewById(R.id.tv_hide);
            mBackButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    SystemUtils.getInstance().sendBack();


                }
            });

            hideBtton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    topLayout.setVisibility(View.GONE);
                    middleLayout.setVisibility(View.GONE);
                    bottomLayout.setVisibility(View.VISIBLE);
                    if (layoutParams!=null) {
                        if (layoutParams.x >= (screenWidth / 2)) {
                            animateToEdge(layoutParams, screenWidth);
                        }
                    }
                }
            });

            bottomLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    topLayout.setVisibility(View.VISIBLE);
                    middleLayout.setVisibility(View.VISIBLE);
                    bottomLayout.setVisibility(View.GONE);
                }
            });

            bottomLayout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    ontochEvent(event);
                    return false;
                }
            });

            mLeftButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    SystemUtils.getInstance().sendLeft();

                }
            });

            mRightButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    SystemUtils.getInstance().sendRight();

                }
            });

            mTopButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    SystemUtils.getInstance().sendUp();

                }
            });

            mDownButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    SystemUtils.getInstance().sendDown();

                }
            });

            mConfirmButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SystemUtils.getInstance().sendCenter();
                }
            });

            mLayout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    ontochEvent(event);
                    return false;
                }


            });

        }
        initlayoutParams();

        // 获取屏幕宽度
        screenWidth = getScreenWidth(context);

        if (isFist) {
            isFist = false;
            windowManager.addView(inflate, layoutParams);
        } else {
            inflate.setVisibility(View.VISIBLE);
        }
    }

    private void initlayoutParams() {
        if (layoutParams == null) {
            layoutParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT);
            layoutParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
            layoutParams.x = 0;
            layoutParams.y = 0;
        }
    }

    private void ontochEvent( MotionEvent event) {
        if (layoutParams != null && layoutParams != null && windowManager != null) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isTounch = true;
                    initialX = layoutParams.x;
                    initialY = layoutParams.y;
                    initialTouchX = event.getRawX();
                    initialTouchY = event.getRawY();
                    touchStartTime = System.currentTimeMillis(); // 记录触摸开始的时间
                    break;
                case MotionEvent.ACTION_UP:
                    long touchEndTime = System.currentTimeMillis(); // 记录触摸结束的时间
                    long touchDuration = touchEndTime - touchStartTime; // 计算触摸持续时间

                    if (touchDuration < 200) { // 200 毫秒作为点击的阈值
                        // 点击事件
                        Log.d("ShowBackButtonViewUtils", "Click event detected");
                        isTounch = false;
//                    onClick(mBackButtonTrackView); // 调用 onClick 方法
                    } else {
                        if (screenWidth <= 0) {
                            screenWidth = getScreenWidth(mContext);
                        }
                        // 吸附功能
                        if (layoutParams.x < (screenWidth / 2)) {
                            animateToEdge(layoutParams, 0);
                        } else {
                            animateToEdge(layoutParams, screenWidth - inflate.getWidth());
                        }
                    }
                    break;// 返回 false 以允许点击事件传递给 OnClickListener
                case MotionEvent.ACTION_MOVE:
                    layoutParams.x = initialX + (int) (event.getRawX() - initialTouchX);
                    layoutParams.y = initialY + (int) (event.getRawY() - initialTouchY);
                    windowManager.updateViewLayout(inflate, layoutParams);
                    break;
            }
        }

    }

    public void hideBackButtonView() {
        if (inflate != null) {
            inflate.setVisibility(View.GONE);
            cleanView();
        }
    }

    public void cleanView() {
        if (inflate != null) {
            windowManager.removeView(inflate);
            layoutParams = null;
            isFist = true;
            windowManager = null;
            inflate = null;
            screenWidth = 0;
        }
    }


    private void animateToEdge(final WindowManager.LayoutParams params, final int targetX) {
        ValueAnimator animator = ValueAnimator.ofInt(params.x, targetX);
        animator.setDuration(300);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                params.x = (Integer) valueAnimator.getAnimatedValue();
                windowManager.updateViewLayout(inflate, params);
            }
        });
        animator.start();
    }

    private int getScreenWidth(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
}
